import axios from "axios"
const todo = {
    state:{
        //所有任务列表
        list:[],
        //文本框的输入内容
        inputValue:'',
        nextId:7,
        viewKey:'all',
    },
    mutations:{
        initList(state,list){
            state.list = list
        },
          //为store里面的inputValue赋值
        setInputValue(state,val){
            state.inputValue = val
        },
          //添加列表项
        addItem(state){
            const obj = {
              id:state.nextId,
              info:state.inputValue,
              done:false
            }
            state.list.push(obj)
            state.nextId++
            state.inputValue = ''
        },
          //根据id删除对应的item事项
        removeItem(state,id){ 
            const i = state.list.findIndex(x => 
              x.id === id
            )
            if(i !== -1){
              //从找到的id的索引开始删除 删除一项
              state.list.splice(i,1)
            }
        },
          //根据id去改变checkbox的选中状态
        changeStatus(state,parms){
            //查找索引
            const i = state.list.findIndex(x => x.id === parms.id)
            if(i !== -1){
              state.list [i].done = parms.status
            }
        },
          //清除已完成的item
        cleanDone(state){
            state.list = state.list.filter(x => x.done === false)
        },
          //修改视图的key值
        changeViewKey(state,key){
            state.viewKey = key
        }
    },
    actions:{
        //获取list json
        getList(context){
        axios.get('/list.json').then((data)=>{
          //console.log(data.data)
          //data里面的data才是数组内容
          context.commit('initList',data.data)
        })
      }
    },
    getters:{
        //未完成任务的个数
        unDoneLength(state){
            //filter x代表list里面的每一项 每一项的done是false就过滤出来 最后过滤出一个新的数组 新的数组的长度就是未完成的个数
            return state.list.filter( x => x.done === false).length
        },
        infolist(state){
            if(state.viewKey === 'all'){
                return state.list
            }
            if(state.viewKey === 'undone'){
                return state.list.filter( x => x.done === false)
            }
            if(state.viewKey === 'done'){
                return state.list.filter( x => x.done === true)
            }
                return state.list
      }
    },
    //namespaced: true,
}
export default todo